package com.cloud.service.impl;

import com.cloud.config.SecurityCloudConfig;
import com.cloud.config.exception.BusinessException;
import com.cloud.service.MediaService;
import com.cloud.util.MediaUtil;
import com.cloud.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

import static com.cloud.util.MediaUtil.*;

/**
 * @author Henry.Song
 * @version 2020/12/21
 * @description
 */
@Service
public class MediaServiceImpl implements MediaService {

    @Autowired
    SecurityCloudConfig securityCloudConfig;

    @Override
    public String convertMediaFile(String filePath, String srcMediaType, String destMediaType) {
        File ffmepgFile = new File(securityCloudConfig.getFfmepgPath());
        if (ffmepgFile.isFile() && ffmepgFile.canExecute()) {
            File srcMediaFile = new File(filePath);
            if (srcMediaFile.isFile()) {
                //String parentPath = srcMediaFile.getParent();
                String destFileName = StringUtil.getAbsoluteFileName(srcMediaFile.getName()) + "."  + destMediaType.toLowerCase();
                File destMediaFile = new File(srcMediaFile.getParent(), destFileName);
                boolean status = false;
                if (MEDIA_AVI.equals(srcMediaType)) {
                    status = MediaUtil.AviToMp4(ffmepgFile.getAbsolutePath(), srcMediaFile.getAbsolutePath(), destMediaFile.getAbsolutePath());
                } else if (MEDIA_FLV.equals(srcMediaType)) {
                    status = MediaUtil.FlvToMp4(ffmepgFile.getAbsolutePath(), srcMediaFile.getAbsolutePath(), destMediaFile.getAbsolutePath());
                } else if (MEDIA_MKV.equals(srcMediaType)) {
                    status = MediaUtil.MkvToMp4(ffmepgFile.getAbsolutePath(), srcMediaFile.getAbsolutePath(), destMediaFile.getAbsolutePath());
                } else if (MEDIA_MOV.equals(srcMediaType)) {
                    status = MediaUtil.MovToMp4(ffmepgFile.getAbsolutePath(), srcMediaFile.getAbsolutePath(), destMediaFile.getAbsolutePath());
                } else if (MEDIA_WMV.equals(srcMediaType)) {
                    status = MediaUtil.WmvToMp4(ffmepgFile.getAbsolutePath(), srcMediaFile.getAbsolutePath(), destMediaFile.getAbsolutePath());
                }
                if (status && destMediaFile.exists()) {
                    return destMediaFile.getPath();
                } else {
                    throw new BusinessException("视频文件转换失败");
                }
            } else {
                throw new BusinessException("请确认转换源文件OK");
            }
        } else {
            throw new BusinessException("请确认媒体转换工具OK");
        }
    }
}
